/**
 * 菜单管理页面
 * @author xiaoxujs
 */

import { useCallback, useEffect, useState } from "react";
import Search from "../../../components/Search";
import { MenuPageBox, MenuPageHeaderBox, MenuPageListBox } from "./style";
import { ISyhtMenuGetMenuAllTree } from "../../../type/ConfigManagement/MenuPage/api";
import { message } from "antd";
import { postSyhtMenuGetMenuAllTree } from "../../../api/ConfigManagement/menuPageApi";
import Tree from "./components/Tree";

const MenuPage = () => {
    const [treeData, setTreeData] = useState<ISyhtMenuGetMenuAllTree[]>([]); // 树状图数据

    const [searchValue, setSearchValue] = useState(''); //检索关键字

    const treeFun = useCallback(
        async () => {
            const { code, msg, data } = await postSyhtMenuGetMenuAllTree() as { code: number, msg: string, data: ISyhtMenuGetMenuAllTree[] };
            if (code === 200) {
       
                setTreeData(data);
            } else {
                message.error(msg);
            }
        },
        [],
    )

    useEffect(() => {
        treeFun();
    }, [treeFun])

    // 检索
    const handleSearch = (value: string) => {
        setSearchValue(value);
        // 第一遍 把所有的show都设置为false
        const newTreeData = JSON.parse(JSON.stringify(treeData)) as ISyhtMenuGetMenuAllTree[];
        const loop = (data: ISyhtMenuGetMenuAllTree[]) => {
            data.forEach((item) => {
                if (item.menuName.includes(value)) {
                    item.show = true;
                } else {
                    item.show = false;
                }
                if (item.children) {
                    loop(item.children)
                }
            })
        }
        loop(newTreeData);
        // 找到所有的父级
        const loopParent = (data: ISyhtMenuGetMenuAllTree[]) => {
            data.forEach((item) => {
                if (item.children) {
                    const isShow = item.children.some((item) => item.show === true);
                    if (isShow) {
                        item.show = true;
                    }
                    loopParent(item.children)
                }
            })
        }
        loopParent(newTreeData);
        setTreeData(newTreeData);
    }

    return (
        <MenuPageBox>
            <MenuPageHeaderBox>
                <div className="left">
                    <div className="left_left_jiantou"></div>
                    <div>全部权限</div>
                    <div className="left_right_jiantou"></div>
                </div>
                <div className="right">
                    <Search placeholder="请搜索关键字" searchChange={(value) => handleSearch(value)} />
                </div>
            </MenuPageHeaderBox>
            <MenuPageListBox>
                <Tree treeData={treeData} setTreeData={setTreeData} searchValue={searchValue} treeFun = {treeFun} />
            </MenuPageListBox>
        </MenuPageBox>
    )
}
export default MenuPage;

